# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
# encoding: utf-8
from store import NewsDB
import pymongo
import json


class Tech163Pipeline(object):
    def process_item(self, item, spider):

        if spider.name != "net163":  return item
        if item.get("news_thread", None) is None: return item

        spec = {"news_thread": item["news_thread"]}
        NewsDB.news0704.update(spec, {'$set': dict(item)}, upsert=True)

        return None


class TemplatePipeline(object):
    collection_name = 'scrapy_items'

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
        )

    # 当spider被开启时，这个方法被调用。
    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    # 当spider被关闭时，这个方法被调用，可以再爬虫关闭后进行相应的数据处理。
    def close_spider(self, spider):
        self.client.close()

    # 每个item pipeline组件都需要调用该方法，这个方法必须返回一个 Item (或任何继承类)对象，
    # 或是抛出 DropItem异常，被丢弃的item将不会被之后的pipeline组件所处理。
    # 参数: item: 由parse方法返回的Item对象(Item对象)
    # spider: 抓取到这个Item对象对应的爬虫对象(Spider对象)
    def process_item(self, item, spider):
        # pymongo的update方法已过时，现在使用 update_many，第一个参数是filter，第二个参数要包括 mongodb的update operator
        # see https: // docs.mongodb.com / manual / reference / operator / update - field /
        # self.db[self.collection_name].insert(dict(item))
        spec = {"news_thread": item["news_thread"]}
        self.db[self.collection_name].update_many(spec, {'$set': dict(item)}, upsert=True)
        return item


class JsonWriterPipeline(object):
    def __init__(self):
        self.file = open('items.jl', 'wb')

    def process_item(self, item, spider):
        line = json.dumps(dict(item)) + "\n"
        self.file.write(line)
        return item
